<html>
    <body>
        <script src="//talkgadget.google.com/hangouts/_/api/hangout.js?v=1.2"></script>
        <table>
        <tr>
           <td id="players"></td>
           <td id="board">
              <canvas id="drop" width=640 height=57></canvas><br>
              <canvas id="canvas" width=640 height=480></canvas>
           </td>
           <td id="commands">
              <button type='button' onClick='initGame();'>New Game</button><br>
              <button type='button' onClick='resetScores();'>Reset Scores</button><br>
              Select players<br>
              <img src='https://sites.google.com/site/connect4hangout/_/rsrc/1362247149375/home/minired.png'><br>
              <div id="red"></div>          
              <img src='https://sites.google.com/site/connect4hangout/_/rsrc/1362247166527/home/miniyellow.png'><br>
              <div id="yellow"></div>          
           </td>
        </tr>
        </table>
        <script>
            var table = new Array();
            var tableImg = null;
            var redCoinImg = null;
            var yellowCoinImg = null;
            var droppingPiece = new Object();
            droppingPiece.color = 0;
            droppingPiece.col = 0;
            droppingPiece.pos = 0;
            droppingPiece.lin = 0;
            droppingPiece.end = 0;
            droppingPiece.speed = 0;
            
            var sharedValues = {};
            
            
            function resetScores() {
               var sharedValues = {};
               var participants = gapi.hangout.getParticipants();
               sharedValues["red"] = "0";
               sharedValues["yellow"] = "0";
               sharedValues["turn"] = "1";
               sharedValues["dropCol"] = "-1";
               sharedValues["dropLin"] = "-1";
               sharedValues["dropColor"] = "0";
               for (var index in participants) {
                  var participant = participants[index];
                  sharedValues[participant.person.id] = '0';
               }
               initGame();
            }

            function onStateChanged(e) {
console.log('onStateChanged - begin');
               sharedValues = gapi.hangout.data.getState();
               var participants = gapi.hangout.getParticipants();
               for (var index in participants) {
                  var participant = participants[index];
                  var score = sharedValues[participant.person.id];
                  document.getElementById(participant.person.id).innerHTML = score;
               }

               var col = sharedValues["dropCol"];
               var row = sharedValues["dropLin"];
               var color = sharedValues["dropColor"];
               if ((col != "-1") && (table[row][col] == 0)) {
                  drop(col, color)
               }
console.log('onStateChanged - end');
            }

            function initGame() {
                for (var l = 0; l < 6; l++) {
                    for (var c = 0; c < 7; c++) {
                        if (table[l] == undefined) {
                            table[l] = new Array();
                        }
                        table[l][c] = 0;
                    }
                }
                document.getElementById("drop").addEventListener('mousemove', onMouseMove, false);
                document.getElementById("drop").addEventListener('mouseup', onMouseUp, false);
                sharedValues["red"] = document.getElementById("redsel").value;
                sharedValues["yellow"] = document.getElementById("yellowsel").value;
                sharedValues["turn"] = "1";
                sharedValues["dropCol"] = "-1";
                sharedValues["dropLin"] = "-1";
                sharedValues["dropColor"] = "0";
console.log("red: " +sharedValues["red"]);
console.log("yellow: " +sharedValues["yellow"]);

                gapi.hangout.data.submitDelta(sharedValues);               
                drawTable()
            }
            
            function onMouseMove (e) {
                var x, y;

                var rect = document.getElementById("drop").getBoundingClientRect();
                x = e.clientX - rect.left;
                y = e.clientY - rect.top;

                var turn = 0;
                if (sharedValues["turn"] == "1") {
                   turn = sharedValues["red"];
                } else {
                   turn = sharedValues["yellow"];
                }

                if (gapi.hangout.getLocalParticipant().person.id == turn) {
                    drawDrop(x, y);
                }
            }
            
            function drawDrop(x, y) {
                x = Math.round((x - 57) / 57);
                sharedValues["dropCol"] = x.toString();
                
                var ctxTable = document.getElementById("drop").getContext('2d');
                ctxTable.clearRect ( 0 , 0 , 640 , 57);
                if (sharedValues["turn"] == "2") {
                    ctxTable.drawImage(yellowCoinImg, 23 + x * 57, 0);
                }
                if (sharedValues["turn"] == "1") {
                    ctxTable.drawImage(redCoinImg, 23 + x * 57, 0);
                }
            }
            
            function onMouseUp(e) {
                var turn = 0;
                if (sharedValues["turn"] == "1") {
                   turn = sharedValues["red"];
                } else {
                   turn = sharedValues["yellow"];
                }

                if (gapi.hangout.getLocalParticipant().person.id == turn) {
                    var ctxTable = document.getElementById("drop").getContext('2d');
                    ctxTable.clearRect ( 0 , 0 , 640 , 57);
                    if (getEmptyPosition(sharedValues["dropCol"]) != -1) {
                       sharedValues["dropColor"] = sharedValues["turn"];
                       sharedValues["turn"] = (sharedValues["turn"] == "1")?"2":"1";
                       sharedValues["dropLin"] = getEmptyPosition(sharedValues["dropCol"]).toString();
                       gapi.hangout.data.submitDelta(sharedValues);    
                    }
                }
console.log('onMouseUp - end');
            }
            
            function loadPieces() {
                var ctxTable = document.getElementById("canvas").getContext('2d');
                tableImg = new Image();
                tableImg.src = "https://sites.google.com/site/connect4hangout/_/rsrc/1362247135856/home/mini_table.png";
                tableImg.onload = function() {
                    redCoinImg = new Image();
                    redCoinImg.src = "https://sites.google.com/site/connect4hangout/_/rsrc/1362247149375/home/minired.png";
                    redCoinImg.onload = function() {
                        yellowCoinImg = new Image();
                        yellowCoinImg.src = "https://sites.google.com/site/connect4hangout/_/rsrc/1362247166527/home/miniyellow.png";
                        yellowCoinImg.onload = onLoadPieces();
                    }
                }
            }
            
            function onLoadPieces() {
                     initGame();
          }
            
            function drawTable() {
                var ctxTable = document.getElementById("canvas").getContext('2d');
                ctxTable.clearRect ( 0 , 0 , 640 , 480);

                for (var l = 0; l < 6; l++) {
                    for (var c = 0; c < 7; c++) {
                        if (table[l][c] == 1) {
                            ctxTable.drawImage(redCoinImg, 23 + c * 57, 11 + l * 57);
                        }
                        if (table[l][c] == 2) {
                            ctxTable.drawImage(yellowCoinImg, 23 + c * 57, 11 + l * 57);
                        }
                    }
                }
                
                if (droppingPiece.color == 1) {
                    ctxTable.drawImage(redCoinImg, 23 + droppingPiece.col * 57, droppingPiece.pos);
                }

                if (droppingPiece.color == 2) {
                    ctxTable.drawImage(yellowCoinImg, 23 + droppingPiece.col * 57, droppingPiece.pos);
                }
                
                ctxTable.drawImage(tableImg,0, 0);
            }
            
            function getEmptyPosition(col) {
                for (var l = 0; l < 6; l++) {
                    if (table[l][col] != 0) {
                        return l - 1;
                    }
                }
                return 5;
            }

            function anime() {
                if (droppingPiece.end > droppingPiece.pos) {
                    droppingPiece.pos += droppingPiece.speed;
                    droppingPiece.speed *= 1.05;
                    window.setTimeout(anime, 1000 / 400);
                } else {
                    table[droppingPiece.lin][droppingPiece.col] = droppingPiece.color;
                    droppingPiece.color = 0;
                    checkWinner();
                }
                drawTable();
            }
            
            function drop(col, colorPiece) {
                droppingPiece.color = colorPiece;
                droppingPiece.col = col;
                droppingPiece.pos = 0;
                droppingPiece.lin = getEmptyPosition(col);
                droppingPiece.end = 11 + getEmptyPosition(col) * 57;
                droppingPiece.speed = 1;
                
                window.setTimeout(anime, 1000 / 60);
            }
            
            function checkWinner() {
                for (var l = 0; l < 6; l++) {
                    for (var c = 0; c < 7; c++) {
                        if (checkLinCol(l , c, 0, 1)) {
                            alert("Winner!");
                        }
                        if (checkLinCol(l , c, 1, 0)) {
                            alert("Winner!");
                        }
                        if (checkLinCol(l , c, 1, 1)) {
                            alert("Winner!");
                        }
                        if (checkLinCol(l , c, 1, -1)) {
                            alert("Winner!");
                        }
                    }
                }                
            }
            
            function checkLinCol(l, c, x, y) {
                var color = table[l][c];
                if (color == 0) {
                    return false;
                }
                var win = false;
                for (count = 1; count < 4; count++) {
                    if ((l + x * count > 5) || (c + y * count > 6)) {
                        return false;
                    }
                    if (table[l + x * count][c + y * count] != color) {
                        return false;
                    }
                }
                if (color == 1) {
                   var id = charedValue["red"];
                }

                return true;
            }
            
            function showParticipants() {
               var participants = gapi.hangout.getParticipants();

               var retVal = '<table>';
               var selVal = '';
               for (var index in participants) {
                  var participant = participants[index];
                  retVal += 
                     '<tr><td><img src="' + participant.person.image.url + '"><br>' + participant.person.displayName + '</td><td>Score<br><div id="' + participant.person.id + '">-1</div></td></tr>';
                  selVal += '<OPTION VALUE="' + participant.person.id + '">' + participant.person.displayName + '</OPTION>';
               }

               retVal += '</table>';
               selVal += '</SELECT>';

               var div = document.getElementById('players');
               document.getElementById('red').innerHTML = '<SELECT id="redsel">' + selVal;
               document.getElementById('yellow').innerHTML = '<SELECT id="yellowsel">' + selVal;

               div.innerHTML = retVal;
            }

            function init() {
               // When API is ready...                                                         
               gapi.hangout.onApiReady.add(
               function(eventObj) {
                  if (eventObj.isApiReady) {
                     showParticipants();                     
                     loadPieces();
                     
                     gapi.hangout.data.onStateChanged.add(
                        function(e) {
                           onStateChanged(e);
                        }
                     );
                  }
               });
            }

            // Wait for gadget to load.                                                       
            gadgets.util.registerOnLoadHandler(init);
        </script>
    </body>    
</html>
